<template>
  <div class="sub-category">
    <van-grid
      :gutter="10"
      :column-num="3"
    >
      <van-grid-item
        v-for="category in categories"
        :key="category.id"
        :icon="category.imageUrl"
        :text="category.title" />
    </van-grid>
  </div>
</template>

<script>
import { getSubCategories } from '@/api/home'
export default {
  name: 'SubCategory',
  data () {
    return {
      categories: []
    }
  },
  created () {
    // console.log('sub, created...')
  },
  beforeRouteEnter (to, from, next) {
    next(async vm => {
      // console.log('sub, beforeRouteEnter')
      setTimeout(() => vm.fetchSubCategories(to), 500)
    })
  },
  async beforeRouteUpdate (to, from, next) {
    this.fetchSubCategories(to)
    next()
  },
  methods: {
    // 获取子分类数据
    async fetchSubCategories (route) {
      // 在动态路径参数中获取主分类的 id 值
      const { cid } = route.params
      /* 查询本地是否有该分类下的子分类数据缓存 */
      const categories = JSON.parse(sessionStorage.getItem('categories')) || []
      const category = categories.find(cat => cat.id === Number(cid)) || {}
      if (category.children) { // 如果有子分类数据，则直接使用
        this.categories = category.children
      } else { // 没有子分类数据，则查询，并缓存
        const result = await getSubCategories(cid)
        this.categories = result.categories
        // 缓存到 sessionStorage 中
        category.children = result.categories
        sessionStorage.setItem('categories', JSON.stringify(categories))
      }
    }
  }
}
</script>

<style lang="less" scoped>

</style>
